/*
*   存储localStorage
*/
export const setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/*
*   获取localStorage
*/

export const getStore = (name) => {
  if (!name) return
  return window.localStorage.getItem(name)
}

/*
*   删除localStorage
*/
export const removeStore = (name) => {
  if (!name) return
  window.localStorage.removeItem(name)
}
/*
*   存储sessionStorage
*/
export const setSession = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.sessionStorage.setItem(name, content)
}

/*
*   获取sessionStorage
*/

export const getSession = (name) => {
  if (!name) return
  return window.sessionStorage.getItem(name)
}

/*
*   删除sessionStorage
*/
export const removeSession = (name) => {
  if (!name) return
  window.sessionStorage.removeItem(name)
}
/*
*   存储cookie 保存7天
*/
export const setCookie = (cname, cvalue, clearday = 7) => {
  let d = new Date()
  d.setTime(d.getTime() + (Number(clearday) * 24 * 60 * 60 * 1000))
  let expires = 'expires=' + d.toUTCString()
  let value = encodeURI(cvalue)  // decodeURI 解码
  // let domainname = window.location.hostname
  document.cookie = cname + '=' + value + ';' + expires
}

/*
*   获取Cookie
*/

export const getCookie = (cname) => {
  let name = cname + '='
  var ca = document.cookie.split(';')
  for (var i = 0; i < ca.length; i++) {
    let c = ca[i].trim()
    if (c.indexOf(name) === 0) {
      let value = decodeURI(c.substring(name.length, c.length))
      return value
    }
  }
  return ''
}

/*
* 删除cookie
*/
export const clearCookie = (name) => {
  setCookie(name, '', -1)
}

/* istanbul ignore next */
export const on = (function () {
  if (document.addEventListener) {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.addEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event && handler) {
        element.attachEvent('on' + event, handler)
      }
    }
  }
})()

/* istanbul ignore next */
export const off = (function () {
  if (document.removeEventListener) {
    return function (element, event, handler) {
      if (element && event) {
        element.removeEventListener(event, handler, false)
      }
    }
  } else {
    return function (element, event, handler) {
      if (element && event) {
        element.detachEvent('on' + event, handler)
      }
    }
  }
})()
